package client.subsistema1;

import beans.Administrador;
import beans.Estudiant;
import beans.ResponsableEvents;
import beans.Usuari;
import common.EOlympicsException;
import common.RemoteInterface;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Albert
 */
public class PantallaBusquedaUsuarios extends javax.swing.JFrame {
    private RemoteInterface remoto;
    private PantallaAdministracioUsuaris pantallaAdministracio;
    private Vector usuaris;
    /**
     * Creates new form PantallaBusquedaUsuarios
     * @param pRemoto objecte remot que s'utilitzarà per fer les conexions al servidor
     * @param pPantallaAdministracio  pantalla d'administració utilitzada per retornar l'usuari seleccionat
     */
    public PantallaBusquedaUsuarios(RemoteInterface pRemoto, PantallaAdministracioUsuaris pPantallaAdministracio) {
        remoto = pRemoto;
        pantallaAdministracio = pPantallaAdministracio;
        
        
        initComponents();
        // center the jframe on screen
        this.setLocationRelativeTo(null);
        
        
        usuaris = new Vector();
        loadTableWithList(usuaris);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        fieldIdentificador = new javax.swing.JTextField();
        labelIdentificador = new javax.swing.JLabel();
        labelNom = new javax.swing.JLabel();
        fieldNom = new javax.swing.JTextField();
        labelApellidos = new javax.swing.JLabel();
        fieldApellido1 = new javax.swing.JTextField();
        botonBuscar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaUsuarios = new javax.swing.JTable();
        botonAceptar = new javax.swing.JButton();
        botonCancelar = new javax.swing.JButton();
        labelApellido2 = new javax.swing.JLabel();
        fieldApellido2 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("i18n/subsistema1/messagesSubsistema1"); // NOI18N
        setTitle(bundle.getString("client.administracio.busqueda.title")); // NOI18N

        labelIdentificador.setText("Identificador:");

        labelNom.setText("Nom:");

        labelApellidos.setText("Cognom 1:");

        botonBuscar.setText("Buscar");
        botonBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Buscar(evt);
            }
        });

        tablaUsuarios.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "Identificador", "Nom", "Cognoms"
            }
        ));
        jScrollPane1.setViewportView(tablaUsuarios);

        botonAceptar.setText("Aceptar");
        botonAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Acceptar(evt);
            }
        });

        botonCancelar.setText("Cancelar");
        botonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Cancelar(evt);
            }
        });

        labelApellido2.setText("Cognom 2:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(17, 17, 17)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(labelNom)
                                        .addGap(56, 56, 56))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(labelApellidos)
                                        .addGap(26, 26, 26)))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(fieldApellido1, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(fieldNom, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(labelIdentificador)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(fieldIdentificador, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(labelApellido2)
                                .addGap(26, 26, 26)
                                .addComponent(fieldApellido2, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(155, 155, 155)
                        .addComponent(botonBuscar))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(69, 69, 69)
                        .addComponent(botonAceptar)
                        .addGap(60, 60, 60)
                        .addComponent(botonCancelar)))
                .addContainerGap(18, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fieldIdentificador, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelIdentificador))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fieldNom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelNom))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fieldApellido1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelApellidos))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fieldApellido2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelApellido2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(botonBuscar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botonAceptar)
                    .addComponent(botonCancelar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Cancela i tanca la pantalla
     * @param evt event que executa l'acció
     */
    private void Cancelar(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Cancelar
        this.dispose();
    }//GEN-LAST:event_Cancelar

    /**
     * Omple la taula amb la llista d'usuaris
     * @param llista Llista amb tots els usuaris
     */
    private void loadTableWithList(Vector llista){
        
        tablaUsuarios.removeAll();

        DefaultTableModel model = new DefaultTableModel();

        model.addColumn("Id");
        model.addColumn("Nom");
        model.addColumn("Cognoms");

        Iterator<Usuari> iterator = llista.iterator();
        while(iterator.hasNext()){
            Usuari usuari = (Usuari)iterator.next();

            String[] resumenCols = {""+usuari.getIdIntern(),usuari.getNom(),usuari.getCognom1()+" "+usuari.getCognom2()};
            model.addRow(resumenCols);

        }

        tablaUsuarios.setModel(model);
    }
    
    /**
     * Realitza una búsqueda al servidor amb els camps omplerts
     * @param evt event que executa l'acció
     */
    private void Buscar(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Buscar
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("i18n/subsistema1/messagesSubsistema1"); // NOI18N
        
        int identificador = 0;
        try{
            identificador = Integer.parseInt(fieldIdentificador.getText());
        }catch (NumberFormatException e){
            
        }
        
        try{
            System.out.print("\nBuscando con: "+fieldIdentificador.getText()+" - "+fieldNom.getText()+" - "+fieldApellido1.getText()+" - "+fieldApellido2.getText()); 
            usuaris = remoto.sub1getBusqueda(identificador, fieldNom.getText(), fieldApellido1.getText(), fieldApellido2.getText());
            if(usuaris!=null){
                loadTableWithList(usuaris);
            }else{
                throw new EOlympicsException(bundle.getString("client.administracio.busqueda.error_busqueda"));
            }
                
        }catch (RemoteException e){
                System.out.print("Remote Exception");
                JOptionPane.showMessageDialog(rootPane, bundle.getString("client.error_rmi"),
                        bundle.getString("client.titol_error_client"), JOptionPane.WARNING_MESSAGE);
        }catch (EOlympicsException e) {
                System.out.print("EOlympicsException");
                JOptionPane.showMessageDialog(rootPane, e.getMessage(),
                        bundle.getString("client.titol_error_client"), JOptionPane.WARNING_MESSAGE);
        }catch (Exception e){
                System.out.print("Exception");
                JOptionPane.showMessageDialog(rootPane, bundle.getString("client.administracio.busqueda.error_busqueda"),
                        bundle.getString("client.titol_error_client"), JOptionPane.WARNING_MESSAGE);
        }
        
    }//GEN-LAST:event_Buscar

    /**
     * Accepta la selecció i envia l'usuari a la pantalla d'administració<br>
     * En cas que no hagi seleccionat cap usuari o hagi seleccionat més d'un, avisarà l'usuari
     * @param evt event que executa l'acció
     */
    private void Acceptar(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Acceptar
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("i18n/subsistema1/messagesSubsistema1"); // NOI18N
        if(tablaUsuarios.getSelectedRowCount()==0){
                JOptionPane.showMessageDialog(rootPane, bundle.getString("client.administracio.busqueda.cap_usuari_seleccionat"),
                        bundle.getString("client.titol_error_client"), JOptionPane.WARNING_MESSAGE);
        }else if(tablaUsuarios.getSelectedRowCount()>1){
                JOptionPane.showMessageDialog(rootPane, bundle.getString("client.administracio.busqueda.multiples_usuaris_seleccionats"),
                        bundle.getString("client.titol_error_client"), JOptionPane.WARNING_MESSAGE);
        }else{
            pantallaAdministracio.pantallaBusquedaDidSelectUser((Usuari)usuaris.get(tablaUsuarios.getSelectedRow()));
        }
    }//GEN-LAST:event_Acceptar

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botonAceptar;
    private javax.swing.JButton botonBuscar;
    private javax.swing.JButton botonCancelar;
    private javax.swing.JTextField fieldApellido1;
    private javax.swing.JTextField fieldApellido2;
    private javax.swing.JTextField fieldIdentificador;
    private javax.swing.JTextField fieldNom;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel labelApellido2;
    private javax.swing.JLabel labelApellidos;
    private javax.swing.JLabel labelIdentificador;
    private javax.swing.JLabel labelNom;
    private javax.swing.JTable tablaUsuarios;
    // End of variables declaration//GEN-END:variables
}
